// pages/job-detail/job-detail.js
Page({
  data: {
    jobId: null,
    job: {},
    baseUrl: 'http://localhost:3000',
    userInfo: null
  },

  onLoad: function(options) {
    if (options.id) {
      this.setData({ jobId: options.id });
      this.loadJobDetails();
      this.loadUserInfo();
    }
  },

  // 加载用户信息
  loadUserInfo: function() {
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.setData({ userInfo });
    }
  },

  // 加载岗位详情
  loadJobDetails: function() {
    const { jobId, baseUrl } = this.data;

    wx.request({
      url: `${baseUrl}/api/jobs/${jobId}`,
      method: 'GET',
      success: (res) => {
        console.log('Job details loaded:', res.data);
        this.setData({ job: res.data });
      },
      fail: (err) => {
        console.error('Failed to load job details:', err);
        wx.showToast({
          title: '加载失败',
          icon: 'none'
        });
      }
    });
  },

  // 投递职位
  applyForJob: function() {
    const { jobId, userInfo, baseUrl } = this.data;

    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '提交中...'
    });

    wx.request({
      url: `${baseUrl}/api/applications`,
      method: 'POST',
      data: {
        job_id: jobId,
        user_id: userInfo.id
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.success) {
          wx.showToast({
            title: '申请成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: '申请失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  }
});